const DutyModel = require('../../db/models/duty')
const fs = require('fs');
const path = require('path');
const xlsx = require('xlsx');

// 下载值班模板
const downloadTemp = async function (ctx, next) {
  let downloadPath = path.resolve(__dirname, '../../public/download/duty.xlsx');
  let data = fs.createReadStream(downloadPath);
  ctx.body = data;
}

// 上传值班记录
const uploadRecord = async function (ctx, next) {
  let file = ctx.request.files.file;
  let data = ctx.request.body;
  let uploadPath = path.resolve(__dirname, '../../public/upload/'); 
  fs.existsSync(uploadPath) || fs.mkdirSync(uploadPath); // 判断路径是否存在，不存在则新建
  let name = file.name.split('.');
  let random = Math.random().toString(36).substr(2);
  let fileName = name[0] + '_' + random + '.' + name[1];
  let filePath = uploadPath + `/${fileName}`;
  // 保存文件
  let saveRes = await saveFiles(file, filePath);
  // 解析excel文件
  let fileData = await readFiles(saveRes, filePath);
  // 入库
  let baseData = await editParamter(data, fileData, fileName);
  await DutyModel.create(baseData).then(() => {
    ctx.body = {
      success: true
    }
  }).catch(err => {
    ctx.body = {
      success: false,
      msg: err.message
    }
  });
}

// 保存文件
const saveFiles = function (file, filePath) {
  let reader = fs.createReadStream(file.path);
  let writer = fs.createWriteStream(filePath);
  return new Promise((resolve) => {
    let stream = reader.pipe(writer);
    stream.on('finish', function (err) {
      resolve(err);
    })
  })
}

// 读文件内容
const readFiles = function (saveRes, filePath) {
  let fileData = [];
  if (!saveRes) {
    let workBook = xlsx.readFile(filePath);
    let sheetNames = workBook.SheetNames; // 返回['sheet1', ...]
    for (const sheetName of sheetNames) {
      let workSheet = workBook.Sheets[sheetName];
      let data = xlsx.utils.sheet_to_json(workSheet);
      fileData.push(data);
    }
  }
  return fileData;
}

// 入库数据整理
const editParamter = function (data, fileData, fileName) {
  let baseData = {
    title: '',
    type: data.dutyType,
    year: data.dutyYear,
    chargePerson: '',
    phone: '',
    createTime: new Date(),
    fileName: fileName,
    reports: []
  }
  if (fileData.length) {
    let info = fileData[0][1].__EMPTY;
    info = info.split('').filter(i => i !== ' ').join('');
    baseData.title = fileData[0][0].__EMPTY;
    baseData.chargePerson = info.slice(info.indexOf('：') + 1, info.indexOf('值班室电话'));
    baseData.phone = info.slice(info.lastIndexOf('：') + 1);
  }
  return baseData;
}

// 查询值班列表
const queryDutyList = async function (ctx, next) {
  let params = ctx.request.query;
  let reg = new RegExp(params.title, 'i');
  let sql = {};
  Object.keys(params).forEach(item => {
    if (item === 'title') {
      sql['$or'] = [{ title: { $regex: reg } }]
    } else {
      sql[item] = params[item]
    }
  })
  let dutyList = await DutyModel.find(sql);
  ctx.body = dutyList;
}

// 删除
const deleteDuty = async function (ctx, next) {
  let params = ctx.request.query;
  let delFile = await DutyModel.findOne(params);
  let delPath = path.resolve(__dirname, '../../public/upload/', delFile.fileName);
  if (fs.existsSync(delPath)) {
    fs.unlinkSync(delPath);
  }
  await DutyModel.deleteMany(params).then(() => {
    ctx.body = {
      success: true
    }
  }).catch(err => {
    ctx.body = {
      success: false,
      msg: err.message
    }
  })
}

// 下载值班表
const downloadDuty = async function (ctx, next) {
  let params = ctx.request.query;
  let target = await DutyModel.findOne(params);
  let filePath = path.resolve(__dirname, '../../public/upload/', target.fileName);
  let data = fs.createReadStream(filePath);
  ctx.body = data;
}

// 查看
const viewDuty = async function (ctx, next) {
  let params = ctx.request.query;
  let target = await DutyModel.findOne(params);
  let filePath = path.resolve(__dirname, '../../public/upload/', target.fileName);
  let fileData = readFiles(false, filePath)[0]; // 取sheet1
  let data = [];
  for (let i = 3; i < fileData.length; i++) {
    data.push({
      dutyTime: fileData[i].__EMPTY,
      dutyLeader: fileData[i].__EMPTY_1,
      leaderPhone: fileData[i].__EMPTY_3,
      dutyMember: fileData[i].__EMPTY_5,
    })
  }
  ctx.body = data;
}

module.exports = {
  downloadTemp,
  uploadRecord,
  queryDutyList,
  deleteDuty,
  downloadDuty,
  viewDuty
}